import request from "@/utils/request";

// 用户模块URL
const MENU_BASE_URL = "/admin";

/**
 * 下载文件
 */
export const downloadFileRequest = (opts: any) => {
    let loadingInstance = loadingStart();
    return new Promise((resolve, reject) => {
        request({
            url: opts.url,
            method: opts.methods,
            [opts.methods.toLocaleUpperCase() == "GET" ? "params" : "data"]:
                opts.data || {},
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            responseType: "blob",
            onDownloadProgress: (progress) =>
                setPace(progress, loadingInstance),
        })
            .then((res) => {
                let fileName = "";
                try {
                    const matchResult = res.headers?.[
                        "content-disposition"
                    ]?.match(/filename='?"?([^'"]+)'?"?$/);
                    if (matchResult && matchResult[1]) {
                        fileName = matchResult[1];
                    }
                } catch (err) {}
                var reader = new FileReader();
                reader.readAsDataURL(res.data); // 转换为base64，可以直接放入a标签href
                reader.onload = function (e) {
                    // console.log('---',e.target.result);//查看有没有接收到数据流
                    downloadFileToLocal(
                        fileName ||
                            opts?.data?.filename ||
                            new Date().getTime().toString(),
                        e.target?.result as string
                    );
                    resolve(res);
                };
            })
            .catch((err) => {
                reject(err);
            });
    }).finally(() => {
        loadingInstance.close();
    });
};

/**
 * 上传文件
 */
export const uploadFileRequest = (opts: any) => {
    const file_data = new FormData();
    for (let k in opts.data) {
        if (opts.data[k] === undefined) {
            continue;
        }
        if (k !== "fileinput" && k !== "file") {
            file_data.append(k, opts.data[k] as string);
        } else if (k == "fileinput" && opts.data.fileinput) {
            file_data.append(k, opts.data.fileinput);
        } else if (k == "file" && opts.data.file) {
            file_data.append(k, opts.data.file);
        }
    }

    let loadingInstance = loadingStart();

    return new Promise((resolve, reject) => {
        request({
            url: opts.url,
            method: opts.methods,
            data: file_data,
            headers: {
                "Content-Type": "multipart/form-data",
            },
            onUploadProgress: (progress) => setPace(progress, loadingInstance),
        })
            .then((res) => {
                loadingInstance.close();
                resolve(res);
            })
            .catch((err) => {
                loadingInstance.close();
                reject(err);
            });
    });
};

// 全屏显示加载中
function loadingStart() {
    return ElLoading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.5)",
    });
}

// 下载到本地
export function downloadFileToLocal(fileName: string, data: string) {
    const a = document.createElement("a");
    a.setAttribute("href", data);
    a.setAttribute("download", fileName);
    a.setAttribute("target", "_blank");
    let clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
}

// 加载中的百分比
function setPace(progress: any, loadingInstance: any) {
    let pace = Math.round((progress.loaded / progress.total!) * 100) + "%";
    loadingInstance.setText(pace);
}

const FileRequest = {
    downloadFileRequest: downloadFileRequest,
    uploadFileRequest: uploadFileRequest,
};

export default FileRequest;
